package com.gateway.springboot.starter.plugin.global;

import com.gateway.common.enums.RpcTypeEnum;
import com.gateway.plugin.api.GatewayPlugin;
import com.gateway.plugin.api.context.GatewayContextBuilder;
import com.gateway.plugin.api.context.GatewayContextDecorator;
import com.gateway.plugin.global.DefaultGatewayContextBuilder;
import com.gateway.plugin.global.GlobalPlugin;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/6 15:55
 **/
@Configuration
@ConditionalOnClass(GlobalPlugin.class)
public class GlobalPluginConfiguration {

    @Bean
    public GatewayPlugin globalPlugin(final GatewayContextBuilder gatewayContextBuilder) {
        return new GlobalPlugin(gatewayContextBuilder);
    }


    /**
     * Gateway context builder.
     *
     * @param decorators the decorators
     * @return the gateway context builder
     */
    @Bean
    @ConditionalOnMissingBean(value = GatewayContextBuilder.class, search = SearchStrategy.ALL)
    public GatewayContextBuilder gatewayContextBuilder(final ObjectProvider<List<GatewayContextDecorator>> decorators) {
        List<GatewayContextDecorator> decoratorList = decorators.getIfAvailable(Collections::emptyList);
        Map<RpcTypeEnum, GatewayContextDecorator> decoratorMap = decoratorList.stream().collect(Collectors.toMap(GatewayContextDecorator::rpcType, e -> e));
        return new DefaultGatewayContextBuilder(decoratorMap);
    }

}
